<?php

/**
 * AJAX CRUD Controller Class
 * The following variables are available in this template:
 * - $this: the CrudCode object
 *
 * @author HaoLV
 */
class UserRoleController extends ControllerBase {

    public function init() {
        ShortUtil::app()->theme = ADMIN_THEME;
        parent::init();
        $this->registerFancybox();
    }

    public function registerFancybox() {
        // Add jQuery library
        // ShortUtil::clientScript()->registerCoreScript('jquery');
        // Add mousewheel plugin (this is optional)
        ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/jquery.mousewheel-3.0.6.pack.js', CClientScript::POS_HEAD);

        // Add fancyBox main JS and CSS files
        ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/jquery.fancybox.js?v=2.0.6');
        ShortUtil::registerCssFile(ShortUtil::themePath() . '/js/fancybox/jquery.fancybox.css?v=2.0.6', 'screen');

        // Add Button helper (this is optional)
        // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-buttons.css?v=1.0.2');
        // ShortUtil::registerCssFile(ShortUtil::themePath().'/js/fancybox/helpers/jquery.fancybox-buttons.js?v=1.0.2','screen');
        // Add Thumbnail helper (this is optional)
        // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-thumbs.css?v=1.0.2');
        // ShortUtil::registerCssFile(ShortUtil::themePath().'/js/fancybox/helpers/jquery.fancybox-thumbs.js?v=1.0.2','screen');
        // Add Media helper (this is optional)
        // ShortUtil::registerScriptFile(ShortUtil::themePath() . '/js/fancybox/helpers/jquery.fancybox-media.js?v=1.0.0');

        if (isset($_GET['ajax']))
            $this->layout = '//layouts/none';
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array('model' => $this->loadModel($id)));
    }

    /**
     * Creates a new model.
     */
    public function actionCreate() {
        $model = new UserRole;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['UserRole'])) {
            $model->attributes = $_POST['UserRole'];
            if ($model->save()) {
                $this->setFlash('UserRole has been created.');
                $this->refresh();
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['UserRole'])) {
            $model->attributes = $_POST['UserRole'];
            if ($model->save()) {
                $this->setFlash('UserRole has been updated.');
                $this->refresh();
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            $ids = $_POST['chk'];
            if (is_array($ids))
                foreach ($ids as $key)
                    $rs = UserRole::model()->deleteByPk($key);
            if (isset($_GET['ajax'])) {
                echo CHtml::tag('div', array('class' => 'flash-success'), "Term ID #{$key} has been deleted.");
                exit;
            } else {
                $this->setFlash("UserRole ID #{$key} has been deleted.");
                $this->redirect(array('index'));
            }
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionIndex() {
        $model = new UserRole('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['UserRole']))
            $model->attributes = $_GET['UserRole'];

        $this->render('index', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = UserRole::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'user-role-form') {
            echo CActiveForm::validate($model);
            ShortUtil::app()->end();
        }
    }

    /* load user in role */

    public function actionLoadUserInRole() {
        $users = User::model()->findAll(array(
            'select' => 'lastname, firstname, t.id',
            'join' => 'JOIN auth_assignment ON auth_assignment.userid = t.id JOIN profiles ON profiles.user_id = t.id',
            'condition' => 'auth_assignment.itemname = :roleName',
            'params' => array(
                ':roleName' => ($_POST['role_name']),
            )
                ));
        echo CHtml::openTag('select', array('name' => 'user-in-role', 'id' => 'user-in-role'));
        echo CHtml::tag('option', array('value' => ''), Util::t('Choose User'));
        foreach ($users as $user => $value) {
            echo CHtml::tag('option', array('value' => $value->id), $value->profile->lastname . " " . $value->profile->firstname);
        }
        echo CHtml::closeTag('select');
    }

    public function actionRoleCheck() {
        $userID = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
        $role = isset($_POST['role']) ? $_POST['role'] : '';

        if ($role != '') {
            $roleArea = UserRole::model()->findAll(array(
                'select' => 'id, controller_name',
                'condition' => 'role = :role',
                'params' => array(
                    ':role' => $role,
                ),
                'group' => 'controller_name'
                    ));
        }

        echo CHtml::openTag('div', array('class' => 'role-box'));
        echo CHtml::openTag('span', array('class' => 'lable-header'));
        echo Util::t("Available Area");
        echo CHtml::closeTag('span');
        echo CHtml::openTag('ul', array('class' => 'role-check-list-root'));

        if ($roleArea) {     //if user was set action role
            foreach ($roleArea as $area => $value) {
                echo CHtml::openTag('li', array()); //print out Controller Name (Suppllier, Product, Brand,....)
                echo CHtml::link($value->controller_name, 'javascript:void(0)', array('value' => $value->controller_name, 'class' => 'check-all-role'));
                $actions = $this->loadControllerActions($value->controller_name);
                echo CHtml::openTag('ul');
                foreach ($actions as $actions => $val) {  //print out Controller Ation (Admin, update, create,... of each controller) 
                    $checked = $this->isUserAllowAction($userID, $value->controller_name, $val->controller_action);
                    echo CHtml::tag('li', array('class' => 'role-check-list'), CHtml::checkBox($value->controller_name . "[" . $val->controller_action . "]", $checked, array('id' => $value->controller_name . "_" . $val->controller_action)) . " " . $val->controller_action);
                }
                echo CHtml::closeTag('ul');
                echo CHtml::closeTag('li');
            }
        }

        echo CHtml::closeTag('ul');
        echo CHtml::closeTag('div');
    }

    public function loadControllerActions($controllerName) {
        $actions = UserRole::model()->findAll(array(
            'select' => 'controller_action, status, user_id',
            'condition' => 'controller_name = :controllerName',
            'params' => array(
                ':controllerName' => $controllerName,
            ),
            'group' => 'controller_action'
                ));
        return $actions;
    }

    public function isUserAllowAction($userID, $controllerName, $controllerAction) {
        $action = UserRole::model()->find(array(
            'select' => 'status',
            'condition' => 'controller_name = :name AND controller_action = :action AND user_id = :userID',
            'params' => array(
                ':name' => $controllerName,
                ':action' => $controllerAction,
                ':userID' => $userID,
            )
                ));

        if ($action)
            return true;
        else
            return false;
    }

    public function actionUpdateUserRole() {
        $name = $_POST['controller_name'];
        $action = $_POST['controller_action'];
        $status = $_POST['status'];
        $userID = $_POST['user_id'];
        $role = $_POST['role'];

        $userRole = UserRole::model()->find(array(
            'condition' => 'user_id = :userID AND controller_name = :controllerName AND controller_action = :controllerAction',
            'params' => array(
                ':userID' => $userID,
                ':controllerName' => $name,
                ':controllerAction' => $action,
            )
                ));

        if ($userRole) {
            echo $status;
            $userRole->status = $status == 'false' ? 0 : 1;
            echo $userRole->status;
            $userRole->update();
            echo "update";
            var_dump($userRole);
        } else {
            $userRole = new UserRole('insert');
            $userRole->user_id = $userID;
            $userRole->role = $role;
            $userRole->controller_name = $name;
            $userRole->controller_action = $action;
            $userRole->status = 1;

            var_dump($userRole->save());
            var_dump($userRole->getErrors());
            echo "insert new";
        }
    }

}
